package com.ilink.ilinkcommon.service.impl.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.PutObjectResult;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.ilinkcommon.utils.oss.OssClient;
import java.io.File;
import java.io.FileInputStream;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
@Slf4j
@Service
@RequiredArgsConstructor
public class OssServiceImpl implements OssService {
    private static final Logger logger = LoggerFactory.getLogger(OssServiceImpl.class);

    private final OssClient ossClient;

    private final List<String> imageExtensions = Arrays.asList("jpg", "jpeg", "png");
    private final List<String> iconExtensions = Arrays.asList("svg", "jpeg", "png", "jpg");
    private final List<String> StudyTreeExtensions = Arrays.asList("mp4", "jpg", "png");
   
    /**
     * @Author ZhangBo
     * @Description 上传文件到OSS
     * @Date 19:36 2024/9/15
     * @Param [file文件, path路径, rename包含后缀的文件名]
     * @return boolean
     **/
    @Override
    public boolean uploadFile(MultipartFile file, String path, String rename) {
        try{
            if (file.isEmpty()) {
                logger.error("上传文件为空");
                return false;
            }
            // 确保目录路径以 '/' 结尾
            if (!path.endsWith("/")) {
                path += "/";
            }
            // 获取OSS客户端
            OSS ossClientInstance = ossClient.getClient();

            // 上传文件到OSS
            //  存放的objectName应该是path+fileName
            PutObjectResult result = ossClientInstance.putObject(ossClient.getBucketName(), path+rename, file.getInputStream());

            // 返回上传成功的URL或其他相关信息
            logger.info("上传成功" + ossClient.getBucketName() + "文件名" + rename);

            return true;
        }catch (IOException e){
            logger.error("上传文件到OSS失败"+e.getMessage());
            return false;
        }
    }
    @Override
    public boolean uploadFile(File file, String path, String rename) {
        try {
            if (!file.exists() || file.length() == 0) {
                System.out.println("上传文件为空或不存在");
                return false;
            }

            // 确保目录路径以 '/' 结尾
            if (!path.endsWith("/")) {
                path += "/";
            }

            // 确保目录存在，不存在则创建
            File directory = new File(path);
            if (!directory.exists()) {
                boolean dirsCreated = directory.mkdirs();  // 一次性创建所有缺失的目录
                if (!dirsCreated) {
                    throw new IOException("无法创建目录: " + directory.getAbsolutePath());
                }
            }

            // 获取OSS客户端
            OSS ossClientInstance = ossClient.getClient();

            // 上传文件到OSS
            // 使用重命名后的文件名作为存储对象的名称
            try (InputStream inputStream = new FileInputStream(file)) {
                PutObjectResult result = ossClientInstance.putObject(ossClient.getBucketName(), path + rename, inputStream);
                System.out.println("上传成功：" + ossClient.getBucketName() + "，文件名：" + rename);
                log.info("上传成功：" + ossClient.getBucketName() + "，文件名：" + rename,result);//result具体返回什么？
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            return true;
        } catch (IOException e) {
//            e.printStackTrace();
            log.error("OSS上传出现错误"+e.getMessage());
            return false;
        }
    }
    @Override
    public boolean uploadFile(byte[] bytes, String path, String rename){
        OSS ossClientInstance = ossClient.getClient();
        try{
            if (!path.endsWith("/")) {
                path += "/";
            }
            PutObjectResult result = ossClientInstance.putObject(ossClient.getBucketName(), path+rename, new ByteArrayInputStream(bytes));
            System.out.println("上传成功" + ossClient.getBucketName() + "文件名" + rename);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 上传文件到制定桶
     * @Date 15:34 2024/11/5
     * @Param [file, path, rename]
     * @return boolean
     **/
    @Override
    public boolean uploadBucketFile(MultipartFile file, String bucketName, String objectName) {
        try{
            if (file.isEmpty()) {
                logger.error("上传文件为空");
                return false;
            }
            // 获取OSS客户端
            OSS ossClientInstance = ossClient.getClient();

            // 上传文件到OSS
            //  存放的objectName应该是path+fileName
            PutObjectResult result = ossClientInstance.putObject(bucketName, objectName, file.getInputStream());

            // 返回上传成功的URL或其他相关信息
            logger.info("上传指定桶成功" + bucketName + "文件名" + objectName);

            return true;
        }catch (IOException e){
            logger.error("上传文件到OSS失败"+e.getMessage());
            return false;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 获取OSS指定对象的URL
     * @Date 19:36 2024/9/15
     * @Param [objectName指定对象名称]
     * @return String
     **/
    @Override
    public String getFileUrl(String objectName){
        try{
            if (objectName == null || objectName.isEmpty()) {
                throw new IllegalArgumentException("从OSS生成URL时objectName不可为空");
            }

            // 获取OSS客户端
            OSS ossClientInstance = ossClient.getClient();

            // 检查对象是否存在。
            boolean doesExist = ossClientInstance.doesObjectExist(ossClient.getBucketName(), objectName);
            if (!doesExist) {
                logger.error(objectName+"不存在，无法得到URL");
                return null;
            }
            // 设置签名URL的过期时间为24小时后（例如）。
            long expireTime = 24 * 60 * 60; // 24 hours in seconds
            Date expiration = new Date(System.currentTimeMillis() + expireTime * 1000);

            // 创建GeneratePresignedUrlRequest对象
            GeneratePresignedUrlRequest requestUrl = new GeneratePresignedUrlRequest(ossClient.getBucketName(), objectName);
            requestUrl.setExpiration(expiration);

            // 生成签名URL
            URL signedUrl = ossClientInstance.generatePresignedUrl(requestUrl);
            System.out.println("生成签名");
            System.out.println(signedUrl);

            // 返回签名URL
            return signedUrl.toString();
        }catch (Exception e){
            logger.error("OSS无法获取指定对象URL"+e.getMessage());
            return null;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 根据指定桶，获取OSS指定对象的URL
     * @Date 19:36 2024/9/15
     * @Param [bucketName指定桶名, objectName指定对象名称]
     * @return String
     **/
    @Override
    public String getBucketFileUrl(String bucketName, String objectName){
        try{
            if (bucketName == null || bucketName.isEmpty()) {
                throw new IllegalArgumentException("从OSS生成URL时bucketName不可为空");
            }
            if (objectName == null || objectName.isEmpty()) {
                throw new IllegalArgumentException("从OSS生成URL时objectName不可为空");
            }

            // 获取OSS客户端
            OSS ossClientInstance = ossClient.getClient();

            // 检查对象是否存在。
            boolean doesExist = ossClientInstance.doesObjectExist(bucketName, objectName);
            if (!doesExist) {
                logger.error(bucketName+"不存在，无法得到URL"+objectName);
                return null;
            }
            // 设置签名URL的过期时间为24小时后（例如）。
            long expireTime = 24 * 60 * 60; // 24 hours in seconds
            Date expiration = new Date(System.currentTimeMillis() + expireTime * 1000);

            // 创建GeneratePresignedUrlRequest对象
            GeneratePresignedUrlRequest requestUrl = new GeneratePresignedUrlRequest(bucketName, objectName);
            requestUrl.setExpiration(expiration);

            // 生成签名URL
            URL signedUrl = ossClientInstance.generatePresignedUrl(requestUrl);
            System.out.println("根据桶名生成签名");
            System.out.println(signedUrl);

            // 返回签名URL
            return signedUrl.toString();
        }catch (Exception e){
            logger.error("OSS无法获取指定对象URL"+e.getMessage());
            return null;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 在OSS中创建目录
     * @Date 19:36 2024/9/15
     * @Param [directory新建文件夹名称, path目标路径]
     * @return boolean
     **/
    @Override
    public boolean createDirectory(String directory, String path){
        try {
            OSS ossClientInstance = ossClient.getClient();
            // 确保新建文件夹以 '/' 结尾
            if (!directory.endsWith("/")) {
                directory += "/";
            }

            // 确保目录路径以 '/' 结尾
//            if (!path.endsWith("/")) {
//                path += "/";
//            }

            // 创建一个空文件（0字节的对象）
            ossClientInstance.putObject(ossClient.getBucketName(), path+directory, new ByteArrayInputStream(new byte[0]));
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 根据指定前缀prefix，返回所有文件
     * @Date 19:36 2024/9/15
     * @Param [prefix指定前缀]
     * @return List<String>
     **/
    @Override
    public List<String> listFiles(String prefix) {
        //  收集该目录下所有文件和子目录
        List<String> fileList = new ArrayList<>();
        try {
            OSS ossClientInstance = ossClient.getClient();

            // 构造ListObjectsRequest请求。
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossClient.getBucketName());

            // 设置正斜线（/）为文件夹的分隔符。
            listObjectsRequest.setDelimiter("/");

            // 列出fun目录下的所有文件和文件夹。
            listObjectsRequest.setPrefix(prefix);

            ObjectListing listing = ossClientInstance.listObjects(listObjectsRequest);

            // 遍历所有文件。
            System.out.println("遍历所有文件:");
            // objectSummaries的列表中给出的是fun目录下的文件。
            for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
                // 过滤掉与前缀相同的对象
                String key = objectSummary.getKey();
                // 过滤掉与前缀相同的对象
                if (!key.equals(prefix)) {
                    fileList.add(key);
                    System.out.println(key);
                }
            }

            // 遍历所有commonPrefix。
            System.out.println("\n遍历所有子目录:");
            // commonPrefixs列表中显示的是fun目录下的所有子文件夹。由于fun/movie/001.avi和fun/movie/007.avi属于fun文件夹下的movie目录，因此这两个文件未在列表中。
            for (String commonPrefix : listing.getCommonPrefixes()) {
                fileList.add(commonPrefix);
                System.out.println(commonPrefix);
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return fileList;
    }

    @Override
    public boolean deleteFile(String pathName) {

        try {
            OSS ossClientInstance = ossClient.getClient();
            // 确保目录路径以 '/' 结尾
            ossClientInstance.deleteObject(ossClient.getBucketName(), pathName);
            logger.info("删除OSS文件{}时成功.",pathName);
            return true;
        } catch (com.aliyun.oss.OSSException e) {
            // 处理特定的OSS异常，并记录日志
            if ("RequestRateTooHigh".equals(e.getErrorCode())) {
                logger.error("请求速率过高，删除文件失败：{}", pathName);
            } else {
                logger.error("OSS异常，删除文件失败：{}，错误信息：{}", pathName, e.getMessage(), e);
            }
            return false;
        } catch (Exception e) {
            logger.error("未知异常，删除文件失败：{}，错误信息：{}", pathName, e.getMessage(), e);
            return false;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 删除指定文件
     * @Date 19:36 2024/9/15
     * @Param [fileName文件名, path路径]
     * @return boolean
     **/
    @Override
    public boolean deleteFile(String fileName, String path) {
        if (!path.endsWith("/")) {
            path += "/";
        }
        String objectName = path + fileName;
        try {
            OSS ossClientInstance = ossClient.getClient();
            // 确保目录路径以 '/' 结尾
            ossClientInstance.deleteObject(ossClient.getBucketName(), objectName);
            logger.info("删除OSS文件{}时成功.",objectName);
            return true;
        } catch (com.aliyun.oss.OSSException e) {
            // 处理特定的OSS异常，并记录日志
            if ("RequestRateTooHigh".equals(e.getErrorCode())) {
                logger.error("请求速率过高，删除文件失败：{}", objectName);
            } else {
                logger.error("OSS异常，删除文件失败：{}，错误信息：{}", objectName, e.getMessage(), e);
            }
            return false;
        } catch (Exception e) {
            logger.error("未知异常，删除文件失败：{}，错误信息：{}", fileName, e.getMessage(), e);
            return false;
        }
    }


    @Override
    public boolean deleteBucketFile(String bucketName, String path, String fileName) {
        if (!path.endsWith("/")) {
            path += "/";
        }
        String objectName = path + fileName;
        try {
            OSS ossClientInstance = ossClient.getClient();
            // 确保目录路径以 '/' 结尾
            ossClientInstance.deleteObject(bucketName, objectName);
            logger.info("删除OSS文件{}时成功.",objectName);
            return true;
        } catch (com.aliyun.oss.OSSException e) {
            // 处理特定的OSS异常，并记录日志
            if ("RequestRateTooHigh".equals(e.getErrorCode())) {
                logger.error("请求速率过高，删除文件失败：{}", objectName);
            } else {
                logger.error("OSS异常，删除文件失败：{}，错误信息：{}", objectName, e.getMessage(), e);
            }
            return false;
        } catch (Exception e) {
            logger.error("未知异常，删除文件失败：{}，错误信息：{}", fileName, e.getMessage(), e);
            return false;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 删除指定目录
     * @Date 19:36 2024/9/15
     * @Param [directory目录路径]
     * @return boolean
     **/
    @Override
    public boolean deleteDirectory(String directory) {
        // 设置安全检查，避免删除整个bucket内的文件
        if (Objects.equals(directory, "") || directory == null || Objects.equals(directory, "/")) {
            return false;
        }

        try {
            OSS ossClientInstance = ossClient.getClient();
            String nextMarker = null;
            ObjectListing objectListing;

            do {
                // 分页列出目录下的对象
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossClient.getBucketName())
                        .withPrefix(directory)
                        .withDelimiter("/")
                        .withMarker(nextMarker);

                objectListing = ossClientInstance.listObjects(listObjectsRequest);
                nextMarker = objectListing.getNextMarker();

                // 删除列出的所有文件
                for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                    ossClientInstance.deleteObject(ossClient.getBucketName(), objectSummary.getKey());
                    // 在每次删除后增加一个短暂的延时，避免触发流量控制
                }

                // 递归删除子目录及其内容
                for (String commonPrefix : objectListing.getCommonPrefixes()) {
                    deleteDirectory(commonPrefix);
                }

            } while (objectListing.isTruncated()); // 如果结果被截断，继续请求下一页
            logger.info("删除OSS文件夹{}时成功.",directory);
            return true;
        } catch (com.aliyun.oss.OSSException e) {
            // 处理特定的OSS异常，并记录日志
            if ("RequestRateTooHigh".equals(e.getErrorCode())) {
                logger.error("请求速率过高，删除目录失败：{}", directory);
            } else {
                logger.error("OSS异常，删除目录失败：{}，错误信息：{}", directory, e.getMessage(), e);
            }
            return false;
        } catch (Exception e) {
            logger.error("未知异常，删除目录失败：{}，错误信息：{}", directory, e.getMessage(), e);
            return false;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 移动文件
     * @Date 19:36 2024/9/15
     * @Param [fileName文件名, ori_path原路径, tar_path目标路径]
     * @return boolean
     **/
    @Override
    public boolean moveFile(String filename, String ori_path, String tar_path) {
        if (!ori_path.endsWith("/")) {
            ori_path += "/";
        }
        if (!tar_path.endsWith("/")) {
            tar_path += "/";
        }

        try {
            OSS ossClientInstance = ossClient.getClient();
            String sourceKey = ori_path + filename;
            String destinationKey = tar_path + filename;

            // 拷贝文件
            CopyObjectResult result = ossClientInstance.copyObject(ossClient.getBucketName(),
                    sourceKey, ossClient.getBucketName(), destinationKey);

            // 删除原文件
            ossClientInstance.deleteObject(ossClient.getBucketName(), sourceKey);

            return true;
        } catch (com.aliyun.oss.OSSException e) {
            // 处理特定的TeaException
            if ("400".equals(e.getErrorCode()) && e.getMessage().contains("Request was denied due to user flow control")) {
                logger.error("OSS操作失败：流量控制限制，文件移动失败。原路径：{}，目标路径：{}，文件名：{}，错误消息：{}",
                        ori_path, tar_path, filename, e.getMessage());
            } else {
                logger.error("OSS TeaException异常，文件移动失败。原路径：{}，目标路径：{}，文件名：{}，错误消息：{}",
                        ori_path, tar_path, filename, e.getMessage(), e);
            }
            return false;
        } catch (Exception e) {
            logger.error("未知异常，文件移动失败。原路径：{}，目标路径：{}，文件名：{}，错误消息：{}",
                    ori_path, tar_path, filename, e.getMessage(), e);
            return false;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 移动目录
     * @Date 19:36 2024/9/15
     * @Param [ori_path原路径, tar_path目标路径]
     * @return boolean
     **/
    @Override
    public boolean moveDirectory(String ori_path, String tar_path) {
        if (!ori_path.endsWith("/")) {
            ori_path += "/";
        }
        if (!tar_path.endsWith("/")) {
            tar_path += "/";
        }

        try {
            OSS ossClientInstance = ossClient.getClient();
            // 列举源路径下所有文件
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossClient.getBucketName()).withPrefix(ori_path);
            ObjectListing objectListing = ossClientInstance.listObjects(listObjectsRequest);

            // 移动每个文件
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                String sourceKey = objectSummary.getKey();
                // 生成目标路径下的文件名
                String destinationKey = tar_path + sourceKey.substring(ori_path.length());

                // 拷贝文件到目标路径
                ossClientInstance.copyObject(ossClient.getBucketName(), sourceKey, ossClient.getBucketName(), destinationKey);

                // 删除源路径下的文件
                ossClientInstance.deleteObject(ossClient.getBucketName(), sourceKey);
            }

            return true;
        } catch (com.aliyun.oss.OSSException e) {
            logger.error("OSS操作失败：文件移动失败。原路径：{}，目标路径：{}，错误消息：{}",
                    ori_path, tar_path, e.getMessage(), e);
            return false;
        } catch (Exception e) {
            logger.error("未知异常，目录移动失败。原路径：{}，目标路径：{}，错误消息：{}",
                    ori_path, tar_path, e.getMessage(), e);
            return false;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 麻紫嫣修改mysql后，执行OSS的移动函数ossService.moveTranFile()
     * @Date 19:36 2024/9/15
     * @Param [ori是指原来的教师/课程/章节/小节/sourceId/mp3/audio.mp3, des是指新的]
     * @return boolean
     **/
    @Override
    public boolean moveTranFile(String ori, String des){
        try {
            OSS ossClientInstance = ossClient.getClient();
            //  拷贝文件
            CopyObjectResult result = ossClientInstance.copyObject(ossClient.getBucketName(),
                    ori, ossClient.getBucketName(), des);

            //  删除文件
            ossClientInstance.deleteObject(ossClient.getBucketName(), ori);

            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
    }

    //  objectName要求teacherId/courseId/chapterId/文件.pdf
    /**
     * @Author ZhangBo
     * @Description 根据URL上传文件到OSS
     * @Date 19:36 2024/9/15
     * @Param [fileUrl文件URL, objectName目标存储对象]
     * @return boolean
     **/
    @Override
    public boolean uploadUrl(String fileUrl, String objectName){

        try {
            OSS ossClientInstance = ossClient.getClient();
            // 从临时URL下载文件
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            InputStream inputStream = connection.getInputStream();

            // 上传文件到自己的OSS
            ossClientInstance.putObject(ossClient.getBucketName(), objectName, inputStream);
            System.out.println("上传oss成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @Author ZhangBo
     * @Description 查找数据集封面
     * @Date 19:36 2024/9/15
     * @Param [bucketName指定桶名, objectBaseName目标对象]
     * @return String
     **/
    @Override
    public String getImageUrl(String bucketName, String objectBaseName) {
        for (String format : imageExtensions) {
            // 获取OSS客户端
            OSS ossClientInstance = ossClient.getClient();

            String objectName = objectBaseName + "." + format;
            logger.info("检查数据集封面是否存在: {}", objectName);
            // 检查数据集封面是否存在是否存在。
            boolean doesExist = ossClientInstance.doesObjectExist(bucketName, objectName);
            if (!doesExist) {
                System.out.println(objectName+"数据集封面不存在，无法得到URL");
                continue;
            }
            // 设置签名URL的过期时间为24小时后（例如）。
            long expireTime = 24 * 60 * 60; // 24 hours in seconds
            Date expiration = new Date(System.currentTimeMillis() + expireTime * 1000);

            // 创建GeneratePresignedUrlRequest对象
            GeneratePresignedUrlRequest requestUrl =
                    new GeneratePresignedUrlRequest(bucketName, objectName);
            requestUrl.setExpiration(expiration);

            // 生成签名URL
            URL signedUrl = ossClientInstance.generatePresignedUrl(requestUrl);
            System.out.println("数据集封面生成临时URL");
            System.out.println(signedUrl);

            // 返回签名URL
            return signedUrl.toString();
        }
        logger.warn("数据集封面没有找到符合的格式: {}", objectBaseName);
        return null; // 如果没有找到符合的格式，返回null
    }

    /**
     * @Author YangZhongjun
     * @Description 查找前端iCon
     * @Date 15:25 2024/9/27
     * @Param [bucketName指定桶名, objectBaseName目标对象]
     * @return String
     **/
    @Override
    public String getFrontendIconUrl(String bucketName, String objectBaseName) {
            OSS ossClientInstance = ossClient.getClient();

            String objectName = objectBaseName;
            logger.info("检查图标是否存在: {}", objectName);
            // 检查数据集封面是否存在是否存在。
            boolean doesExist = ossClientInstance.doesObjectExist(bucketName, objectName);
            if (!doesExist) {
                System.out.println(objectName+"图标不存在，无法得到URL");
            }
            // 设置签名URL的过期时间为24小时后（例如）。
            long expireTime = 300; // 300 seconds
            Date expiration = new Date(System.currentTimeMillis() + expireTime * 1000);

            // 创建GeneratePresignedUrlRequest对象
            GeneratePresignedUrlRequest requestUrl =
                new GeneratePresignedUrlRequest(bucketName, objectName);
            requestUrl.setExpiration(expiration);

            // 生成签名URL
            URL signedUrl = ossClientInstance.generatePresignedUrl(requestUrl);
            System.out.println("图标生成临时URL");
            System.out.println(signedUrl);

            // 返回签名URL
            return signedUrl.toString();
    }

    /**
     * @Author ZhangBo
     * @Description 查找模型iCon
     * @Date 19:36 2024/9/15
     * @Param [bucketName指定桶名, objectBaseName目标对象]
     * @return String
     **/
    @Override
    public String getIconUrl(String bucketName, String objectBaseName) {
        for (String format : iconExtensions) {
            // 获取OSS客户端
            OSS ossClientInstance = ossClient.getClient();

            String objectName = objectBaseName + "." + format;
            logger.info("检查模型广场图标是否存在: {}", objectName);
            // 检查数据集封面是否存在是否存在。
            boolean doesExist = ossClientInstance.doesObjectExist(bucketName, objectName);
            if (!doesExist) {
                System.out.println(objectName+"模型广场图标不存在，无法得到URL");
                continue;
            }
            // 设置签名URL的过期时间为24小时后（例如）。
            long expireTime = 24 * 60 * 60; // 24 hours in seconds
            Date expiration = new Date(System.currentTimeMillis() + expireTime * 1000);

            // 创建GeneratePresignedUrlRequest对象
            GeneratePresignedUrlRequest requestUrl =
                    new GeneratePresignedUrlRequest(bucketName, objectName);
            requestUrl.setExpiration(expiration);

            // 生成签名URL
            URL signedUrl = ossClientInstance.generatePresignedUrl(requestUrl);
            System.out.println("模型广场图标生成临时URL");
            System.out.println(signedUrl);

            // 返回签名URL
            return signedUrl.toString();
        }
        logger.warn("模型广场图标没有找到符合的格式: {}", objectBaseName);
        return null; // 如果没有找到符合的格式，返回null
    }

    /**
     * @Author 郑千鹤
     * @Description //查找技能树封面图
     * @Date 18:17 2024/9/16
     * @Param [bucketName, objectBaseName]
     * @return java.lang.String
     **/
    @Override
    public String getStudyTreeResourceUrl(String bucketName, String objectBaseName) {
        for (String format : StudyTreeExtensions) {
            // 获取OSS客户端
            OSS ossClientInstance = ossClient.getClient();

            String objectName = objectBaseName + "." + format;
            logger.info("检查学习广场技能树资源是否存在: {}", objectName);
            boolean doesExist = ossClientInstance.doesObjectExist(bucketName, objectName);
            if (!doesExist) {
                System.out.println(objectName+"学习广场技能树资源不存在");
                continue;
            }
            // 设置签名URL的过期时间为24小时后（例如）。
            long expireTime = 24 * 60 * 60; // 24 hours in seconds
            Date expiration = new Date(System.currentTimeMillis() + expireTime * 1000);

            // 创建GeneratePresignedUrlRequest对象
            GeneratePresignedUrlRequest requestUrl =
                new GeneratePresignedUrlRequest(bucketName, objectName);
            requestUrl.setExpiration(expiration);

            // 生成签名URL
            URL signedUrl = ossClientInstance.generatePresignedUrl(requestUrl);
            System.out.println("学习广场技能树资源URL：");
            System.out.println(signedUrl);

            // 返回签名URL
            return signedUrl.toString();
        }
        logger.warn("没有找到符合的格式: {}", objectBaseName);
        return null; // 如果没有找到符合的格式，返回null
    }
    @Override
    public String uploadFileAndGetUrl(MultipartFile file, String bucketName, String objectName) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                logger.error("上传文件为空");
                return null;
            }

            // 获取OSS客户端
            OSS ossClientInstance = ossClient.getClient();

            // 上传文件到OSS
            PutObjectResult result = ossClientInstance.putObject(bucketName, objectName, file.getInputStream());
            logger.info("上传文件成功: " + bucketName + " 文件名: " + objectName);

            // 检查对象是否存在
            boolean doesExist = ossClientInstance.doesObjectExist(bucketName, objectName);
            if (!doesExist) {
                logger.error(objectName + " 不存在，无法得到URL");
                return null;
            }

            // 设置签名URL的过期时间
            long expireTime = 24 * 60 * 60; // 24小时过期
            Date expiration = new Date(System.currentTimeMillis() + expireTime * 1000);

            // 创建生成签名URL的请求
            GeneratePresignedUrlRequest requestUrl = new GeneratePresignedUrlRequest(bucketName, objectName);
            requestUrl.setExpiration(expiration);

            // 生成签名URL
            URL signedUrl = ossClientInstance.generatePresignedUrl(requestUrl);
            logger.info("生成签名URL成功: " + signedUrl);

            // 返回生成的签名URL
            return signedUrl.toString();

        } catch (IOException e) {
            logger.error("上传文件到OSS失败: " + e.getMessage());
            return null;
        } catch (Exception e) {
            logger.error("获取OSS对象URL失败: " + e.getMessage());
            return null;
        }
    }

}
